<template>
	<view>
		<view class="loginBox">
			<image class="header-image" src="https://oos-cn.ctyunapi.cn/front-end/static/static/noLogin.png"></image>
			<view class="loginTip">
				<view>欢迎使用充电APP</view>
				<view>将获取您的手机号以便快速登录</view>
			</view>

			<view>
				<view class="form">
					<view class="form_item flex-row-start">
						<image src="https://oos-cn.ctyunapi.cn/front-end/static/static/phone.png" mode=""></image>
						<input class="form_item_input flex_1" :value="form.phoneNo" @input='changePhone' type="number"
							placeholder="请输入手机号码">

					</view>
					<view class="form_item flex-row-start">
						<image src="https://oos-cn.ctyunapi.cn/front-end/static/static/Verification code.png" mode=""></image>
						<input type="number" class="form_item_input flex_1" :value="form.codeNum" @input='changeCode'
							placeholder="请输入验证码">
						<text class="code" @tap="getCode">获取验证码</text>
					</view>
				</view>
				<button class="btn2" @tap="login">登录</button>
			</view>


			<view class="agree">
				<image class="img" :src="isAgree ? sellerNo=='jw'?'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkbox_sel-blue.png':'https://oos-cn.ctyunapi.cn/front-end/static/static/checkbox_sel.png' : 'https://oos-cn.ctyunapi.cn/front-end/static/static/checkbox.png'"
					@tap="onAgree"></image>
				<view class="txt">
					<span @tap="onAgree">我已阅读并同意</span>
					<text @tap="goUserAgreement">《用户使用协议》</text>
					和
					<text @tap="goPrivacyPolicy">《隐私协议》</text>
				</view>
			</view>
		</view>

		<u-popup mode='center' :show="showTip" @close="onPopupBtn"
			custom-style="padding:34rpx;background: #FFFFFF;border-radius: 16rpx;width:630rpx;">
			<view class="popupTitle">温馨提示</view>
			<view class="popupTxt">
				使用前，请你详细阅读
				<a @tap="goUserAgreement">《用户使用协议》</a>
				和
				<a @tap="goPrivacyPolicy">《隐私政策》</a>
				并同意后，开始使用充电服务。
			</view>
			<view class="popupBtn">
				<view class="popupBtn1" @tap="onPopupBtn" data-type="close">取消</view>
				<view class="popupBtn2" @tap="onPopupBtn" data-type="open">确定</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	'use strict';

	var app = getApp();

	var https_1 = require('api/https.js');

	var util_1 = require('utils/util.js');

	var throttle = new util_1.Throttle();
	export default {
		components: {},
		data() {
			return {
				sellerNo :app.globalData.sellerNo,
				userInfo: {},
				form: {
					phoneNo: '13267731941',
					codeNum: '055618'
				}, // 表单信息
				userInfo:{}, //用戶信息
				hasUserInfo: false,
				canIUse: uni.canIUse('button.open-type.getUserInfo'),
				canIUseGetUserProfile: false,
				isAgree: false,
				showTip: false,
				encryptedData: '',
				openId: '',
				session_key: '',
				unionId: '',
				hasPhoneNumber: ''
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function() {
			var that = this;
			this.setLoginInfo()
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {},
		methods: {
			setLoginInfo() {
				let that = this
				let type
				let platform = uni.getSystemInfoSync().platform
				let {
					sellerNo,
					sellerId
				} = app.globalData
				if (platform == 'ios') {
					type = '0'
				} else if (platform == 'android') {
					type = '1'
				}

				this.form.type = type
				this.form.sellerNo = sellerNo
				this.form.sellerId = sellerId

				// 获取ip地址 会跨域
				uni.request({
					url: 'http://pv.sohu.com/cityjson?ie=utf-8',
					method: 'POST',
					success: (res) => {
				  const reg = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/;
						let ip = reg.exec(res.data);
						that.form.ip = ip[0]
					}
				})
			},

			// 手机号码改变
			changePhone(e) {
				this.form.phoneNo = e.detail.value
			},
			// 验证码改变
			changeCode(e) {
				this.form.codeNum = e.detail.value
			},
			// 获取验证码
			getCode() {
				if (!this.isAgree) return this.showTip = true
				if (!this.checkForm(['phoneNo'])) return
				let {
					phoneNo,
					sellerId,
					sellerNo
				} = this.form
				https_1.getIdCodeApp({
					phoneNo,
					sellerId,
					sellerNo,
					type: '0'
				}).then(res => {
					console.log(res, this.form)
					if (res.code == 0) {
						uni.showToast({
							title: '验证码已发送至您的手机',
							icon: 'none',
						})
					}
				})
			},
			// 登录按钮事件
			login() {
				let that = this;
				if (!this.isAgree) return this.showTip = true
				if (!this.checkForm(['phoneNo', 'codeNum'])) return
				uni.showLoading({
					title: '加载中......'
				});
				this.wxGetUserInfo().then(userInfo => {
					let {
						phoneNo,
						codeNum,
						type,
						ip,
						sellerNo,
						sellerId
					} = this.form

					let {
						openId,
						nickName: name,
						avatarUrl: icon,
						unionId
					} = userInfo

					this.loginApp({
						codeNum,
						openId,
						type,
						name,
						icon,
						phoneNo,
						ip,
						unionId,
						sellerNo,
						sellerId
					}).then(res => {
						this.userInfo = userInfo
						this.setUserInfo(res)
						uni.hideLoading();
					}).catch(err =>{
						// console.log(err,'err')
						uni.hideLoading();
					})
				})
			},
			// 登录完成设置缓存
			setUserInfo(res) {
				try {
					uni.setStorageSync('tel', res.msg)
					uni.setStorageSync('token', res.data)
					uni.setStorageSync('newPeople', false)
					uni.setStorageSync('openId', this.userInfo.openId)
					uni.setStorageSync('unionId', this.userInfo.unionId)
					uni.navigateBack()
					https_1.citareaListByNamey({
						name: uni.getStorageSync('cityName'),
					}).then((res) => {
						if (res.code == 0) {
							uni.setStorageSync('cityId', res.data.id);
							uni.setStorageSync('currentCityId', res.data.id);
						}
					})
				} catch (error) {
					// console.log('error :>> ', error);
				}
			},
			// APP登录接口
			loginApp(data) {
				return new Promise((resolve, reject) => {
					https_1.loginApp(data).then(res => {
						console.log(res, 'lalal')
						if (res.code == 0) {
							resolve(res)
						} else if (res.code == 4) {
							// 手机号未注册
							this.registerApp(data).then(res => {
								resolve(res)
							}).catch(err=>{
								reject(res)
							})
						} else {
							reject(res)
							// 验证码错误
							uni.showToast({
								title: res.msg || '错误代码',
								icon: 'none',
							})
						}
					})
				})

			},
			// APP注册接口
			registerApp(data) {
				return new Promise((resolve, reject) => {
					https_1.registerApp(data).then(res => {
						if (res.code == 0) {
							resolve(res)
						} else {
							reject(res)
						}
					})
				})
			},
			// 校验表单方法
			checkForm(names = []) {
				let {
					phoneNo,
					codeNum
				} = this.form
				let reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/; //11位手机号码正则
				let state = true
				if (names.includes('phoneNo')) {
					if (!phoneNo) {
						uni.showToast({
							title: '请输入手机号码',
							icon: 'none',
						})
						state = false
					} else if (!reg_tel.test(phoneNo)) {
						uni.showToast({
							title: '手机号填写有误',
							icon: 'none',
						})
						state = false
					}
				}
				if (state && names.includes('codeNum')) {
					if (!codeNum) {
						uni.showToast({
							title: '请输入验证码',
							icon: 'none',
						})
						state = false
					}
				}

				return state
			},
			// 同意协议后获取手机号
			getPhoneNumber: function(e) {
				var that = this;
				var openId = this.openId;
				var unionId = this.unionId;
				var session_key = this.session_key;

				if (e.detail.errMsg == 'getPhoneNumber:ok' && e.detail.encryptedData != '') {
					//获取手机号成功  // 调用登录接口
					uni.showLoading({
						title: '加载中...'
					});
					https_1
						.loginCheck({
							openId: openId,
							unionId: unionId,
							phoneKey: session_key,
							encryptedData: e.detail.encryptedData,
							name: this.userInfo.nickName || null,
							icon: this.userInfo.avatarUrl || 'https://oos-cn.ctyunapi.cn/front-end/static/static/photo.png',
							iv: e.detail.iv,
							sellerNo: app.globalData.sellerNo,
							type: '3'
						})
						.then(function(res) {
							// console.log("🍒 ~ file: login.ts ~ line 66 ~ getPhoneNumber ~ res", res)
							if (res.code == 0) {
								//手机号已注册过 重新获取token登录
								uni.hideLoading();

								try {
									uni.setStorageSync('tel', res.msg);
									uni.setStorageSync('token', res.data);
									uni.setStorageSync('newPeople', false);
									uni.setStorageSync('openId', openId);
									https_1
										.citareaListByNamey({
											name: uni.getStorageSync('cityName')
										})
										.then(function(res) {
											if (res.code == 0) {
												uni.setStorageSync('cityId', res.data.id);
												uni.setStorageSync('currentCityId', res.data.id);
											}
										});
									uni.navigateBack();
								} catch (error) {
									// console.log('error :>> ', error);
								}
							} else {
								//手机号未注册
								uni.showLoading({
									title: '未注册'
								});
								https_1
									.login({
										openId: openId,
										unionId: unionId,
										type: '3',
										name: that.userInfo.nickName || null,
										icon: that.userInfo.avatarUrl || 'https://oos-cn.ctyunapi.cn/front-end/static/static/photo.png',
										phoneKey: session_key,
										encryptedData: e.detail.encryptedData,
										iv: e.detail.iv,
										sellerNo: app.globalData.sellerNo,
										inviterMemberId: null //邀请人Id
									})
									.then(function(res) {
										uni.hideLoading();

										if (res.code == 0 || res.code == 2) {
											//注册成功
											uni.setStorageSync('token', res.data);
											uni.setStorageSync('tel', res.msg);
											uni.setStorageSync('newPeople', true);
											https_1
												.citareaListByNamey({
													name: uni.getStorageSync('cityName')
												})
												.then(function(res) {
													if (res.code == 0) {
														uni.setStorageSync('cityId', res.data.id);
														uni.setStorageSync('currentCityId', res.data.id);
													}
												});
											uni.navigateBack();
										} else {
											// 绑定失败
											uni.showToast({
												title: res.msg,
												icon: 'none',
												duration: 2000
											});
										}
									})['catch'](function() {
										uni.hideLoading();
									});
							}
						})['catch'](function() {
							uni.hideLoading();
						});
				} else {
					uni.showToast({
						title: '获取手机号失败',
						icon: 'none',
						duration: 2000
					});
				}
			},

			//未同意协议点击获取手机号
			getAgree: function() {
				if (!this.isAgree) {
					this.setData({
						showTip: true
					});
				}

				return !this.isAgree;
			},

			// 获取个人信息
			getUserProfile: function() {
				var that = this;

				if (this.getAgree()) {
					return;
				}

				throttle.use(function() {
					// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
					uni.getUserProfile({
						desc: '用于完善会员资料',
						success: function(res) {
							that.setData({
								userInfo: res.userInfo,
								hasUserInfo: true
							});
						}
					});
				}, 3000);
			},
			// APP唤起微信授权
			wxGetUserInfo() {
				return new Promise((resolve, reject) => {
					uni.getProvider({
						service: 'oauth',
						success: function(res) {
							if (~res.provider.indexOf('weixin')) {
								uni.login({
									provider: 'weixin',
									success: function(loginRes) {
										uni.getUserInfo({
											provider: 'weixin',
											success: function(infoRes) {
												let userInfo = {
													...infoRes.userInfo,
													...loginRes.authResult
												}
												resolve(userInfo)
												console.log(userInfo, '用户信息');
											},
											fail(err) {
												reject(err)
												console.log(err,
													'getUserInfoError')
											}
										})
									},
									fail(err) {
										reject(err)
										console.log(err, 'loginError')
									}
								})
							}
						},
						fail(err) {
							reject(err)
							console.log(err, 'getProviderError')
						}
					})
				})
			},

			// 同意/取消协议
			onAgree: function() {
				this.setData({
					isAgree: !this.isAgree
				});
			},

			// 用户使用协议
			goUserAgreement: function() {
				if(app.globalData.sellerNo=='lp'){
                uni.navigateTo({
                url: '/agreement/pages/userAgreement/userAgreement-lp'
            });
            }else{
            uni.navigateTo({
                url: '/agreement/pages/userAgreement/userAgreement'
            });
        }
			},

			// 隐私政策
			goPrivacyPolicy: function() {
				if(app.globalData.sellerNo=='lp'){
                uni.navigateTo({
                url: '/agreement/pages/privacyPolicy/privacyPolicy-lp'
            });
            }else{
            uni.navigateTo({
                url: '/agreement/pages/privacyPolicy/privacyPolicy'
            });
        }
			},

			// 未同意协议对话框
			onPopupBtn: function(e) {
				var type = e.currentTarget.dataset.type;

				if (type === 'open') {
					this.setData({
						isAgree: true,
						showTip: false
					});
				} else {
					this.setData({
						showTip: false
					});
				}
			}
		}
	};
</script>
<style lang="less">
	@import url("@/commin/flex.less");
</style>
<style scoped>
	/* pages/login/login.wxss */
	/*颜色*/
	/*数字*/
	/*文字溢出隐藏*/
	/*固定布局*/
	/* grid是（布局 */
	/*宽高*/
	/* 字体大小*/
	/* 行高 */
	/* 圆角 */
	/* 外边距 */
	/* 内边距 */
	/* 实边框 */
	/* 虚边框 */
	/* 定位  */
	page {
		background-color: #f5f7fa;
	}

	.loginBox {
		width: 750rpx;
		justify-content: center;
		align-items: center;
		text-align: center;
	}

	.loginBox .header-image {
		width: 369rpx;
		height: 179rpx;
		margin: 163rpx 0 32rpx 0;
	}

	.loginBox .loginTip {
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #b8b8b8;
		line-height: 45rpx;
	}

	.loginBox .btn1 {
		width: 632rpx;
		height: 88rpx;
		line-height: 88rpx;
		background: var(--btnColor);
		border-radius: 44rpx 44rpx 44rpx 44rpx;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #fff;
		opacity: 0.97;
		margin: 83rpx 59rpx 30rpx 59rpx;
	}

	.loginBox .btn2 {
		width: 632rpx;
		height: 88rpx;
		line-height: 88rpx;
		background: var(--btnColor);
		border-radius: 44rpx 44rpx 44rpx 44rpx;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #fff;
		opacity: 0.97;
		margin: 80rpx 59rpx 30rpx 59rpx;
	}

	.loginBox .agree {
		display: flex;
		align-items: center;
	}

	.loginBox .agree .img {
		width: 30rpx;
		height: 30rpx;
		margin: 0 18rpx 0 66rpx;
	}

	.loginBox .agree .txt {
		font-size: 26rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #606266;
	}

	.loginBox .agree .txt text {
		color: var(--textColor);
	}

	.popupTitle {
		font-size: 34rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #1a1a1a;
	}

	.popupTxt {
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #303133;
		line-height: 45rpx;
		margin: 31rpx 0 83rpx 0;
	}

	.popupTxt a {
		color: var(--textColor);
	}

	.popupBtn {
		display: flex;
	}

	.popupBtn .popupBtn1 {
		width: 270rpx;
		height: 88rpx;
		line-height: 88rpx;
		border: 1rpx solid #909399;
		border-radius: 44rpx 44rpx 44rpx 44rpx;
		text-align: center;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #909399;
	}

	.popupBtn .popupBtn2 {
		width: 270rpx;
		height: 88rpx;
		line-height: 88rpx;
		background: linear-gradient(105deg, #2b99ff, #1b8cf5);
		box-shadow: 0rpx 3rpx 6rpx 0rpx rgba(0, 110, 212, 0.3);
		border-radius: 44rpx 44rpx 44rpx 44rpx;
		text-align: center;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #fff;
		margin-left: 24rpx;
	}

	.form {
		width: 600rpx;
		margin: 0 auto;
		margin-top: 80rpx;
	}

	.form .form_item {
		border-bottom: 1rpx solid #D2D2D2;
		height: 80rpx;
	}

	.form .form_item image {
		width: 18rpx;
		height: 18rpx;
		margin-right: 20rpx;
	}

	.form .form_item input {
		text-align: start;
	}

	.form .form_item .code {
		background: var(--btnColor);
		font-size: 22rpx;
		color: #fff;
		padding: 16rpx 30rpx;
		margin-right: 20rpx;
		border-radius: 4rpx;
	}

	.uni-input-placeholder {
		text-align: start;
	}
</style>
